<template>
  <div>
    <!-- 面包屑导航 -->
    <div class="flex items-center text-sm text-gray-600 mb-6">
     <a href="/" class="hover:text-[#C32A31]">首页</a>
     <span class="mx-2">/</span>
     <span class="text-gray-800 font-medium">新闻详情</span>
    </div>

    <div class="text-center">

    <div v-if="loading">
      加载中...
    </div>

    <div v-else-if="error">
      <FailedToFetch v-if="error === 'Failed to fetch'"/>
      <div v-else>
        加载失败: {{ error }}
      </div>
    </div>

    <div v-else-if="articleData">
      <!-- 文章标题 -->
      <div class="max-w-7xl mx-auto px-4 mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-4 text-left">{{ articleData.title }}</h1>
        <div class="flex items-center space-x-8 text-sm text-gray-600">
          <div class="flex items-center">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
            </svg>
            {{ articleData.category }}
          </div>
          <div class="flex items-center">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            {{ formatDateTime(articleData.pub_time) }}
          </div>
          <div v-if="articleData.section" class="flex items-center">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
            </svg>
            {{ articleData.section }}
          </div>
        </div>
      </div>
      <div class="max-w-7xl mx-auto px-4">
        <div class="flex gap-8">
          <!-- 主要内容区域 -->
          <div class="flex-1">
            <div class="bg-white shadow-sm rounded-lg p-8">
              <div id="article-content" class="prose prose-lg max-w-none" v-html="articleData.content_html"></div>
            </div>
          </div>

          <!-- 右侧边栏 -->
          <div class="w-64 hidden lg:block">
            <div class="bg-white border border-gray-200 shadow-sm">
              <!-- 标题栏 -->
              <div class="bg-[#C32A31] text-white px-4 py-3">
                <h3 class="font-medium text-base flex items-center">
                  <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"></path>
                  </svg>
                  最新动态
                </h3>
              </div>

              <!-- 文章列表 -->
              <div class="p-4">
                <div v-if="sidebarLoading" class="text-center py-4">
                  <div class="text-sm text-gray-500">加载中...</div>
                </div>
                <div v-else-if="latestArticles && latestArticles.length > 0" class="space-y-3">
                  <div v-for="article in latestArticles" :key="article.newsId" class="group">
                    <router-link
                      :to="{ name: 'NewsDetail', params: { newsId: article.newsId } }"
                      class="block hover:bg-gray-50 p-2 -m-2 rounded transition-colors"
                    >
                      <div class="flex items-start space-x-0.5">
                        <div class="flex-shrink-0 mt-1.5">
                          <div class="w-1.5 h-1.5 bg-[#C32A31] rounded-full"></div>
                        </div>
                        <div class="flex-1 min-w-0 relative">
                          <div class="text-gray-900 group-hover:text-[#C32A31] font-medium leading-5 line-clamp-2 text-sm pr-12">
                            {{ article.title }}
                          </div>
                          <div class="absolute bottom-0 right-0 text-xs text-gray-500 flex items-center">
                            <svg class="w-3 h-3 mr-1 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            {{ formatSidebarDate(article.pub_time || article.pubTime || article.publishTime || article.createTime || article.create_time || article.time || article.date) }}
                          </div>
                        </div>
                      </div>
                    </router-link>
                  </div>
                </div>
                <div v-else class="text-center py-4">
                  <div class="text-sm text-gray-500">暂无最新动态</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      暂无文章数据。
    </div>
    </div>
  </div>
</template>

<style scoped>
/* 文章内容样式 */
#article-content {
  line-height: 1.7;
  font-size: 16px;
  color: #374151;
}

#article-content img {
  max-width: 100%;
  height: auto;
  margin: 2em auto;
  display: block;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

#article-content p {
  margin-bottom: 1.2em;
  text-align: justify;
}

#article-content h1,
#article-content h2,
#article-content h3,
#article-content h4,
#article-content h5,
#article-content h6 {
  margin-top: 2em;
  margin-bottom: 0.8em;
  font-weight: 600;
  color: #1f2937;
}

#article-content h1 { font-size: 1.8em; }
#article-content h2 { font-size: 1.5em; }
#article-content h3 { font-size: 1.3em; }

#article-content ul,
#article-content ol {
  margin: 1.2em 0;
  padding-left: 1.5em;
}

#article-content li {
  margin-bottom: 0.5em;
}

#article-content blockquote {
  border-left: 4px solid #C32A31;
  margin: 1.5em 0;
  background-color: #f9fafb;
  padding: 1rem;
  border-radius: 0 6px 6px 0;
  font-style: italic;
}

#article-content table {
  width: 100%;
  border-collapse: collapse;
  margin: 1.5em 0;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
}

#article-content th,
#article-content td {
  padding: 0.75rem;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

#article-content th {
  background-color: #f9fafb;
  font-weight: 600;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .lg\:block {
    display: none !important;
  }
}

/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>

<script setup lang="js">
import FailedToFetch from "../errors/FailedToFetch.vue";
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { articleApi } from '../../utils/api';

// 获取路由参数
const route = useRoute();
const newsId = computed(() => route.params.newsId);

// 1. 定义响应式数据
const articleData = ref(null); // 用于存储文章数据，初始值为 null
const loading = ref(false);    // 用于控制加载状态，初始值为 false
const error = ref(null);       // 用于存储错误信息，初始值为 null

// 侧边栏最新动态数据
const latestArticles = ref([]); // 最新文章列表
const sidebarLoading = ref(false); // 侧边栏加载状态

// 2. 处理HTML内容，移除特定格式的文本
const processHtmlContent = (html) => {
  if (!html) return '';

  console.log('原始HTML内容长度:', html.length);

  // 直接使用宽松模式匹配所有包含text-align:center;text-indent:2em的段落
  const pattern = /<p\s+style="[^"]*text-align:center;\s*text-indent:2em;[^"]*">.*?<\/p>/g;

  const beforeLength = html.length;
  const processedHtml = html.replace(pattern, (match) => {
    console.log('替换格式:', match);
    return '';
  });

  if (beforeLength !== processedHtml.length) {
    console.log('替换成功，替换前长度:', beforeLength, '替换后长度:', processedHtml.length);
  } else {
    console.log('未找到匹配内容，HTML未变化');
  }

  return processedHtml;
};

// 3. 格式化日期时间为北京时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';

  try {
    // 创建日期对象
    const date = new Date(dateTimeStr);

    // 转换为北京时间（UTC+8）
    const beijingDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);

    // 格式化为 XXXX年X月X日 XX:XX:XX
    const year = beijingDate.getUTCFullYear();
    const month = beijingDate.getUTCMonth() + 1;
    const day = beijingDate.getUTCDate();
    const hours = beijingDate.getUTCHours().toString().padStart(2, '0');
    const minutes = beijingDate.getUTCMinutes().toString().padStart(2, '0');
    const seconds = beijingDate.getUTCSeconds().toString().padStart(2, '0');

    return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
  } catch (err) {
    console.error('日期格式化错误:', err);
    return dateTimeStr;
  }
};

// 侧边栏日期格式化函数（简单显示年月日）
const formatSidebarDate = (dateTimeStr) => {
  if (!dateTimeStr) {
    return '无日期';
  }

  try {
    const date = new Date(dateTimeStr);

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '日期错误';
    }

    // 简单显示年月日格式：2024-01-15
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
  } catch (err) {
    console.error('日期格式化错误:', err);
    return '日期错误';
  }
};

// 4. 获取最新文章列表（用于侧边栏）
const fetchLatestArticles = async () => {
  sidebarLoading.value = true;

  try {
    // 获取最新5篇文章，按发布时间倒序排列
    const response = await articleApi.getArticleList({
      limit: 5,
      page: 1
    });

    // 处理响应数据
    let articles = [];

    if (response && response.code === 200 && response.data) {
      if (Array.isArray(response.data)) {
        articles = response.data;
      } else if (response.data.list && Array.isArray(response.data.list)) {
        articles = response.data.list;
      }
    } else if (Array.isArray(response)) {
      articles = response;
    } else if (response && response.list && Array.isArray(response.list)) {
      articles = response.list;
    }

    // 确保只显示5篇文章
    latestArticles.value = articles.slice(0, 5);
  } catch (err) {
    console.error('获取最新文章失败:', err);
    latestArticles.value = [];
  } finally {
    sidebarLoading.value = false;
  }
};

// 5. 定义获取文章数据的函数
const fetchArticle = async () => {
  loading.value = true; // 开始加载时设置为 true
  error.value = null;   // 清空之前的错误信息

  try {
    // 使用axios通过API工具获取文章数据
    const data = await articleApi.getArticleDetail(newsId.value);

    // 如果返回的是标准响应格式（包含code和data）
    if (data && data.code === 200) {
      articleData.value = data.data;
    } else {
      // 如果直接返回数据
      articleData.value = data;
    }

    // 如果获取到了文章数据，处理HTML内容
    if (articleData.value && articleData.value.content_html) {
      articleData.value.content_html = processHtmlContent(articleData.value.content_html);
    }
  } catch (e) {
    error.value = e.message || '加载文章数据失败'; // 捕获错误，并设置 error 信息
    console.error('获取文章数据失败:', e);        // 可以在控制台打印更详细的错误信息
  } finally {
    loading.value = false; // 加载完成后设置为 false (无论成功或失败)
  }
};

// 6. 监听路由变化，当newsId改变时重新获取文章
watch(newsId, (newId, oldId) => {
  if (newId && newId !== oldId) {
    fetchArticle();
    // 不需要重复获取侧边栏数据，因为最新文章列表不会频繁变化
  }
}, { immediate: false });

// 7. 在组件挂载后执行数据请求
onMounted(() => {
  fetchArticle();
  fetchLatestArticles();
});
</script>
